package com.varian.boot.listener;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.varian.misc.ApplicationStartedCustomizer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.availability.AvailabilityChangeEvent;
import org.springframework.boot.availability.ReadinessState;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ben
 * @since 2024/6/22
 */
@Slf4j
@RequiredArgsConstructor
public class ApplicationStartedListener {

    private final List<ApplicationStartedCustomizer> customizers;

    @Async
    @EventListener(
            value = AvailabilityChangeEvent.class,
            condition = "event.state.equals(T(org.springframework.boot.availability.ReadinessState).ACCEPTING_TRAFFIC)"
    )
    public void onApplicationEvent(AvailabilityChangeEvent<ReadinessState> event) {
        ThreadUtil.safeSleep(1000L);
        String message = customizers.stream().map(e -> {
            e.afterExecute(event);
            return e.afterMessage(event);
        }).collect(Collectors.joining(StrUtil.LF));
        log.info("\n\n{}\n", message);
    }
}
